package com.example.everying.controller.system;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.everying.model.entity.system.SysDict;
import com.example.everying.model.job.ScheduleJob;
import com.example.everying.service.system.ScheduleJobService;
import com.example.everying.service.system.ScheduledTaskService;
import com.example.everying.utils.PageParam;
import com.example.everying.utils.QuartzUtils;
import com.example.everying.utils.RandomUtil;
import com.example.everying.utils.Result;
import io.swagger.annotations.Api;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * @program: everything
 * @description: 定时器任务
 * @author: zw
 * @create: 2025-07-09 09:15
 **/
@Slf4j
@RestController
@Api(tags = "定时器任务")
@RequestMapping("/scheduled")
public class ScheduledTaskController {

    @Resource
    private QuartzUtils quartzUtils;
    @Resource
    private ScheduledTaskService sysDict;
    @Resource
    private ScheduleJobService jobService;

    @PostMapping("/page")
    public Result page(@RequestBody PageParam<ScheduleJob> query){
        Page<ScheduleJob> pageParam = new Page<>(query.getCurrent(), query.getLimit());
        IPage<ScheduleJob> pageModel = jobService.slectPage(pageParam,query.getQuery());
        return Result.success(pageModel);
    }

    @PostMapping("/add")
    public Result<String> addJob(@RequestBody ScheduleJob job) {
        try {
            // 从页面参数生成Cron表达式（示例：2025-07-10 15:30:00）
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date executeTime = sdf.parse(job.getDescription()); // 假设description存储执行时间
            job.setCronExpression(quartzUtils.generateCronExpression(executeTime));
            job.setId(RandomUtil.generateId());
            job.setCreateTime(LocalDateTime.now());
            jobService.save(job);
            // 创建定时任务
            quartzUtils.createJob(job);
            return Result.success("任务添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("任务添加失败：" + e.getMessage());
        }
    }
    @PostMapping("/update")
    private Result updateJob(@Valid @RequestBody ScheduleJob job) {
        boolean update = jobService.updateById(job);
        if (!update) {
            return Result.fail("任务修改失败");
        }
        return Result.success("任务修改成功");
    }

    @DeleteMapping("/{id}")
    private Result updateJob(@PathVariable @NotBlank(message = "任务ID不能为空") String id) {
        UpdateWrapper<ScheduleJob> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id",id);
        updateWrapper.set("is_delete",1);
        boolean del = jobService.update(updateWrapper);
        if (!del) {
            return Result.fail("任务删除失败");
        }
        return Result.success("任务删除成功");
    }
    @PostMapping("/list")
    public List<SysDict> list(){
        QueryWrapper<SysDict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code","art_weight");
        return sysDict.list(wrapper);
    }

}
